<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:c="livcos.org/ns/cosmos"
	xmlns="http://www.w3.org/1999/xhtml"
	xmlns:f="livcos.org/ns/xslt/function"
	exclude-result-prefixes="c f">

	<xsl:import href="../../style/base.xsl"/>

	<xsl:param name="scope" select="'view'"/>
	<xsl:param name="ref"/>
	<xsl:param name="_rev"/>

	<xsl:variable name="absRef" select="f:find-data-object($ref)"/>
	<xsl:variable name="absRefUri">
		<xsl:value-of select="$absRef"/>
		<xsl:if test="($scope != 'view') and not(contains($ref, '?'))">
			<xsl:text>.</xsl:text>
			<xsl:value-of select="$scope"/>
		</xsl:if>
		<xsl:if test="normalize-space($_rev) != ''">
			<xsl:value-of select="if (contains($ref, '?')) then '&amp;' else '?'"/>
			<xsl:text>_rev=</xsl:text>
			<xsl:value-of select="$_rev"/>
		</xsl:if>
	</xsl:variable>

	<xsl:variable name="content" select="if (doc-available($absRefUri)) then doc($absRefUri) else /.."/>
	
	<xsl:template match="/">
		<xsl:choose>
			<xsl:when test="name(*) != 'context'">
				<xsl:apply-templates select="*"/>
			</xsl:when>
			<xsl:when test="normalize-space($ref) = ''">
				<html>
					<body>
						<h2>No "ref" Parameter Specified!</h2>
						<p>Please specify the "ref" parameter for this view!</p>
						<p>For example:</p>
						<p>
							<code><xsl:value-of select="$taskDefId"/>.html?ref=document_object_ID</code>
						</p>
						<p> The "ref" path can be relative to the view object ID (<xsl:value-of select="$taskDefId"
							/>). </p>
					</body>
				</html>
			</xsl:when>
			<xsl:when test="$absRef = ''">
				<job:read obj="/livcos.org/web/sys/feedback/ObjectNotFound" scope="view"
					xmlns:job="livcos.org/ns/process/job">
					<job:param name="objUri" value="{$ref}"/>
				</job:read>
			</xsl:when>
			<xsl:when test="$content/*">
				<xsl:apply-templates select="$content"/>
			</xsl:when>
			<xsl:when test="doc-available(concat($absRef, '.meta'))">
				<job:read obj="/livcos.org/web/sys/feedback/NoData"
					xmlns:job="livcos.org/ns/process/job">
					<job:param name="ref" value="{$absRef}"/>
					<job:param name="scope" value="{$scope}"/>
				</job:read>
			</xsl:when>
			<xsl:otherwise>
				<job:read obj="/livcos.org/web/sys/feedback/ObjectNotFound"
					xmlns:job="livcos.org/ns/process/job">
					<job:param name="objUri" value="{$absRef}"/>
				</job:read>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

</xsl:stylesheet>
